package com.kuaimacode.kframework.api.service.weixin;

import com.alibaba.fastjson.JSONObject;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import weixin.popular.bean.sns.Jscode2sessionResult;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.service.weixin
 * @Description: created by IntelliJ IDEA
 * @date 2019-07-19 09:42
 */
@Slf4j
@Service
public class WeixinApiService {

    @Value("${weixin.applets.appId}")
    private String weixinAppId;
    @Value("${weixin.applets.appSecret}")
    private String weixinSecret;

    public Jscode2sessionResult getMsgByAppletsLoginCode(String loginCode) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", weixinAppId);
        params.put("secret", weixinSecret);
        params.put("js_code", loginCode);
        params.put("grant_type", "authorization_code");
        String response;
        log.info("appletsLogin request: {}", JSONObject.toJSONString(params));
        try {
            response = HttpUtil.getString("https://api.weixin.qq.com/sns/jscode2session", params);
        } catch (Exception e) {
            log.error("调用微信登陆api异常", e);
            throw new ServerInternalErrorException(ErrorEnum.WEI_XIN_LOGIN_API_EXCEPTION);
        }

        log.info("wechat jscode2session response: [{}], js_code: {}", response, loginCode);
        return JSONObject.parseObject(response, Jscode2sessionResult.class);
    }
}
